<?php
namespace app\home\controller;

use \app\common\controller\Homebase;
use think\Db;
use \think\Loader;

class Level extends Basic
{
    public function _initialize()
    {
        $this->menu[0]['text'] = '等级列表';
        $this->menu[0]['url']  = 'index';
        $this->assign('third_menu', $this->menu);
        $this->level = Loader::model('UserLevel');
    }

    public function index()
    {
        $list = $this->level->showLevel();
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function edit(){
    	if (input('id')) {
    		$data = $this->level->getLevelById(input('id'));
    		$this->assign('data', $data);
    	}
    	return $this->fetch('add');
    }
    public function add()
    {
        return $this->fetch();
    }
    
    public function level_add()
    {
        $data['level_name']  = input('level_name');
        $data['amount']      = input('amount');
        $data['discount']    = input('discount');
        $data['description'] = input('description');
        $res  = $this->level->checkLevel($data);
        if ($res){
        	return $this->ret->setCode(1)->setMsg($res['msg'])->toJson();
        }
        $res  = $this->level->levelAdd($data);
    	if ($res['code']) {
	    	return $this->ret->setCode(0)->setAsk("新增成功,是否继续？")->toJson();
	    } else {
	    	return $this->ret->setCode(1)->setMsg($res['msg'])->toJson();
	    }
    }

    public function level_edit()
    {
        $data['level_name']  = input('level_name');
        $data['amount']      = input('amount');
        $data['discount']    = input('discount');
        $data['description'] = input('description');
        $res  = $this->level->checkLevel($data);
        if ($res){
        	return $this->ret->setCode(1)->setMsg($res['msg'])->toJson();
        }
        $res                 = $this->level->levelAdd($data, input('id'));
        if ($res['code']) {
	    	return $this->ret->setCode(0)->setAsk("修改成功,是否继续？")->toJson();
	    } else {
	    	return $this->ret->setCode(1)->setMsg($res['msg'])->toJson();
	    }
    }
    public function del() {
        $id = input('id');
        $res = Db::name("UserLevel")->where("level_id",$id)->delete();
        if($res) {
            return $this->ret->setCode(0)->setMsg("删除成功")->toJson();
        }else {
            return $this->ret->setCode(1)->setMsg("删除失败")->toJson();
        }
    }
    public function listorder()
    {
    	$res = listorder('level_id', input('id/a'), input('order/a'), $this->level);
    	if ($res) {
    		return $this->ret->setCode(0)->setMsg('排序更新成功')->setReload()->toJson();
    	} else {
    		return $this->ret->setCode(1)->setMsg('排序更新失败')->toJson();
    	}
    }
}
